﻿using BW.Mes.WinForms.Process.ProcessModel.Model;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.CustomerForm;
using static BW.Mes.WinForms.BasicData.LineForm1;
using static BW.Mes.WinForms.BasicData.ProductForm;
using static BW.Mes.WinForms.Process.OperationModel.OperationDataForm;
using static BW.Mes.WinForms.Process.ProcessDataForm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

// 引用七牛云帮助类
using BW.Mes.WinForms.Production.Order;


namespace BW.Mes.WinForms.Production.Order
{
    public partial class UpdateOrderForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _OerderUrl = "http://120.26.197.100:8022";
        private readonly string _apiProcessUrl = "http://120.26.197.100:8022";
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private readonly string _qiniuDomain = "syv7j21aq.hb-bkt.clouddn.com"; // 七牛云存储域名
        private readonly string _qiniuPrefix = "Pic/"; // 七牛云存储前缀目录


        private OrderForm.WorkOrderModel _orderModel;
        // 添加调试标志
        private readonly bool _isDebug = true; // 调试模式标志

        // 添加调试日志方法
        private void DebugLog(string message)
        {
            if (_isDebug)
            {
                Console.WriteLine($"[七牛云调试] {DateTime.Now:HH:mm:ss.fff}: {message}");

                // 同时写入日志文件
                try
                {
                    string logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "qiniu_debug.log");
                    File.AppendAllText(logPath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}{Environment.NewLine}");
                }
                catch
                {
                    // 忽略日志写入错误
                }
            }
        }

        /// <summary>
        /// 构造函数注入
        /// </summary>
        public UpdateOrderForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            _apiProcessUrl = "http://120.26.197.100:8022"; // 替换为您的实际API基础URL
            _apiBaseUrl = "http://120.26.197.100:8022";

            // 初始化文件对话框
            xtraOpenFileDialog1 = new XtraOpenFileDialog();
            xtraOpenFileDialog1.Filter = "所有文件 (*.*)|*.*|图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png";
            xtraOpenFileDialog1.Title = "选择文件";


            //工序路线
            ShowOperation();
            //产品主数据
            ShowMasterData();
            //产线
            ShowLine();
            //客户
            ShowClient();
        }

        public UpdateOrderForm(OrderForm.WorkOrderModel model)
        {
            InitializeComponent();
            _orderModel = model; //保存模型的引用


            // 初始化文件对话框
            xtraOpenFileDialog1 = new XtraOpenFileDialog();
            xtraOpenFileDialog1.Filter = "所有文件 (*.*)|*.*|图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png";
            xtraOpenFileDialog1.Title = "选择文件";

            // 初始化HttpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 先加载数据源
            _ = LoadInitialData();



            if (model != null)
            {
                Code.Text = model.Code;
                ProductionType.Text = model.ProductionType;
                // Client和Line的值设置需要在数据加载后进行
                ProductionCount.Text = model.ProductionCount.ToString();
                BeginTime.DateTime = model.BeginTime;
                EndTime.DateTime = model.EndTime;
                Whether.EditValue = model.Whether;

                // 添加图片和备注的回显
                if (!string.IsNullOrEmpty(model.Img))
                {
                    try
                    {
                        // 显示文件名在按钮上
                        Img.Text = Path.GetFileName(model.Img);
                        // 保存完整路径在Tag和ToolTip中
                        Img.Tag = model.Img;
                        Img.ToolTip = model.Img;
                    }
                    catch
                    {
                        // 如果解析文件名失败，直接显示路径
                        Img.Text = "已上传文件";
                        Img.Tag = model.Img;
                        Img.ToolTip = model.Img;
                    }
                }
                else
                {
                    Img.Text = "选择文件";
                }

                ProductionDesc.Text = model.ProductionDesc;
            }
            // 加载初始数据（产线和客户数据）
            //_ = LoadInitialData();
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <returns></returns>
        private async Task LoadInitialData()
        {
            try
            {
                //工序路线
                await ShowOperation();
                //产品主数据
                await ShowMasterData();
                //产线
                await ShowLine();
                //客户
                await ShowClient();

                // 在数据加载完成后，设置选中值
                if (_orderModel != null)
                {
                    // 设置客户和产线的选中值
                    Client.EditValue = _orderModel.Client;
                    Masterdata.EditValue = _orderModel.Masterdata;
                    Line.EditValue = _orderModel.Line;
                    Operation.EditValue = _orderModel.Operation;

                    // 调试信息
                    Console.WriteLine($"设置工序路线ID: {_orderModel.Operation}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载初始数据失败: {ex.Message}");
                // 不抛出异常，继续执行
            }
        }

        /// <summary>
        /// 实体类
        /// </summary>
        public class WorkOrderModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 编码
            /// </summary>
            public string Code { get; set; }
            /// <summary>
            /// 类型  （正常、自建工单）
            /// </summary>
            public string ProductionType { get; set; }

            /// <summary>
            /// 客户  （外键）
            /// </summary>
            public long Client { get; set; }
            /// <summary>
            /// 产品主数据(外键)
            /// </summary>
            public long Masterdata { get; set; }
            /// <summary>
            /// 产线 （外键）
            /// </summary>
            public long Line { get; set; }
            /// <summary>
            /// 工序路线 （外键）
            /// </summary>
            public long Operation { get; set; }

            /// <summary>
            /// 工序进度
            /// </summary>
            public string Progress { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public int ProductionCount { get; set; }
            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime BeginTime { get; set; }
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime EndTime { get; set; }
            /// <summary>
            /// 是否允许有跳工序
            /// </summary>
            public string Whether { get; set; }
            /// <summary>
            /// 上传文件
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string ProductionDesc { get; set; }

            /// <summary>
            /// 添加人
            /// </summary>
            public string CreatedBy { get; set; }
        }
        /// <summary>
        /// 实体类
        /// </summary>
        public class WorkOrderUpdateModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 编码
            /// </summary>
            public string Code { get; set; }
            /// <summary>
            /// 类型  （正常、自建工单）
            /// </summary>
            public string ProductionType { get; set; }

            /// <summary>
            /// 客户  （外键）
            /// </summary>
            public long Client { get; set; }
            /// <summary>
            /// 产品主数据(外键)
            /// </summary>
            public long Masterdata { get; set; }
            /// <summary>
            /// 产线 （外键）
            /// </summary>
            public long Line { get; set; }
            /// <summary>
            /// 工序路线 （外键）
            /// </summary>
            public long Operation { get; set; }

            /// <summary>
            /// 工序进度
            /// </summary>
            public string Progress { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public int ProductionCount { get; set; }
            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime BeginTime { get; set; }
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime EndTime { get; set; }
            /// <summary>
            /// 是否允许有跳工序
            /// </summary>
            public string Whether { get; set; }
            /// <summary>
            /// 上传文件
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string ProductionDesc { get; set; }

            /// <summary>
            /// 添加人
            /// </summary>
            public string CreatedBy { get; set; }
        }


        /// <summary>
        /// 修改按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Update_Click(object sender, EventArgs e)
        {
            try
            {

                var update = new WorkOrderUpdateModel
                {
                    Id = _orderModel.Id, // 使用当前模型的ID
                    Code = Code.Text.Trim(),
                    ProductionType = ProductionType.Text.Trim(),
                    Client = Client.EditValue != null ? Convert.ToInt64(Client.EditValue) : 0,
                    Masterdata = Masterdata.EditValue != null ? Convert.ToInt64(Masterdata.EditValue) : 0,
                    Line = Line.EditValue != null ? Convert.ToInt64(Line.EditValue) : 0,
                    Operation = Operation.EditValue != null ? Convert.ToInt64(Operation.EditValue) : _orderModel.Operation, // 如果未选择则保持原值
                    Progress = _orderModel.Progress, // 保持原进度不变
                    ProductionCount = !string.IsNullOrEmpty(ProductionCount.Text) ? Convert.ToInt32(ProductionCount.Text) : 0,
                    BeginTime = BeginTime.DateTime,
                    EndTime = EndTime.DateTime,
                    Whether = Whether.EditValue?.ToString(),
                    // 使用保存在Tag中的七牛云URL，如果没有则使用原始值
                    Img = Img.Tag != null ? Img.Tag.ToString() : _orderModel.Img,
                    ProductionDesc = ProductionDesc.Text.Trim(),
                    CreatedBy = _orderModel.CreatedBy // 保持原创建者不变
                };

                // 调试信息
                Console.WriteLine($"更新后的工序路线ID: {update.Operation}");
                Console.WriteLine($"提交的图片URL: {update.Img}");

                // 发送更新请求
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(_OerderUrl);

                    // 创建JSON数据
                    var json = JsonConvert.SerializeObject(update);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送PUT请求进行更新
                    var response = await client.PutAsync("/T4/ProduceModel/UploadWorkorder", content);

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("更新成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        var errorMessage = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"更新失败：{response.ReasonPhrase}\n{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"更新过程中出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 照片上传
        private async void Img_Click(object sender, EventArgs e)
        {
            try
            {
                // 使用XtraOpenFileDialog选择文件
                xtraOpenFileDialog1.Filter = "图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png|所有文件 (*.*)|*.*"; // 设置筛选器
                if (xtraOpenFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    // 用户选了文件，可获取路径
                    string filePath = xtraOpenFileDialog1.FileName;

                    try
                    {
                        // 显示上传中提示
                        XtraMessageBox.Show("文件上传中，请稍候...");

                        // 检查文件大小
                        FileInfo fileInfo = new FileInfo(filePath);
                        if (fileInfo.Length > 10 * 1024 * 1024) // 10MB限制
                        {
                            XtraMessageBox.Show("文件大小超过10MB，请选择较小的文件");
                            return;
                        }

                        // 调用WebApi上传图片
                        string imageUrl = await UploadImageToWebApiAsync(filePath);

                        if (!string.IsNullOrEmpty(imageUrl))
                        {
                            // 将文件名显示在按钮上
                            Img.Text = Path.GetFileName(filePath);
                            // 在Img.Tag中保存URL
                            Img.Tag = imageUrl;
                            // 记录调试日志
                            DebugLog($"图片上传成功，URL: {imageUrl}");

                            XtraMessageBox.Show("文件上传成功！");
                        }
                        else
                        {
                            DebugLog("图片上传失败，返回的URL为空");
                            XtraMessageBox.Show("文件上传失败，请稍后重试");
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugLog($"图片上传异常: {ex.Message}");
                        XtraMessageBox.Show($"文件上传失败：{ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                DebugLog($"选择文件异常: {ex.Message}");
                XtraMessageBox.Show($"上传文件时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 通过WebApi上传图片到七牛云
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <returns>上传成功返回图片URL，失败返回null</returns>
        private async Task<string> UploadImageToWebApiAsync(string filePath)
        {
            try
            {
                DebugLog($"开始上传图片: {filePath}");

                // 创建MultipartFormDataContent
                using (var content = new MultipartFormDataContent())
                {
                    // 读取文件内容
                    byte[] fileBytes = File.ReadAllBytes(filePath);
                    var fileContent = new ByteArrayContent(fileBytes);

                    // 添加文件内容到请求
                    content.Add(fileContent, "file", Path.GetFileName(filePath));

                    // 创建HttpClient
                    using (var client = new HttpClient())
                    {
                        // 设置WebApi基地址
                        client.BaseAddress = new Uri(_apiBaseUrl);
                        DebugLog($"API基地址: {_apiBaseUrl}");

                        // 发送请求
                        DebugLog("发送上传请求...");
                        var response = await client.PostAsync("/T4/ProduceModel/UploadImages", content);
                        DebugLog($"上传响应状态: {response.StatusCode}");

                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            DebugLog($"上传响应内容: {responseContent}");

                            // 如果响应是纯文本（文件名），直接构建URL
                            if (!string.IsNullOrEmpty(responseContent) && !responseContent.StartsWith("{"))
                            {
                                // 假设响应内容是文件名，需要构建完整URL
                                string fileName = responseContent.Trim();
                                string imageUrl = $"http://{_qiniuDomain}/{_qiniuPrefix}{fileName}"; // 使用配置的七牛云域名和前缀
                                DebugLog($"构建图片URL: {imageUrl}");
                                return imageUrl;
                            }

                            // 如果是JSON格式，尝试解析
                            if (responseContent.StartsWith("{"))
                            {
                                try
                                {
                                    var result = JsonConvert.DeserializeObject<UploadResult>(responseContent);
                                    if (result != null && result.Success && !string.IsNullOrEmpty(result.Url))
                                    {
                                        DebugLog($"从JSON解析URL: {result.Url}");
                                        return result.Url;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DebugLog($"JSON解析异常: {ex.Message}");
                                }
                            }

                            // 返回原始响应作为备选
                            if (!string.IsNullOrEmpty(responseContent))
                            {
                                DebugLog($"返回原始响应作为URL: {responseContent}");
                                return responseContent.Trim();
                            }
                        }

                        DebugLog("上传失败，返回null");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                DebugLog($"上传过程异常: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 上传结果类
        /// </summary>
        public class UploadResult
        {
            public bool Success { get; set; }
            public string Url { get; set; }
            public string Message { get; set; }
        }
        #endregion

        #region 下拉框数据加载
        /// <summary>
        /// 工序路线下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowOperation()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiProcessUrl}/T5/OperationModel/ShowOperation");
                response.EnsureSuccessStatusCode();


                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                if (jsonObject["pagingData"] != null)
                {
                    string dataJson = jsonObject["pagingData"].ToString();
                    var process = JsonConvert.DeserializeObject<List<OperationModel>>(dataJson);

                    if (process != null && process.Count > 0)
                    {
                        // 输出调试信息
                        Console.WriteLine($"工序路线数据加载成功，共 {process.Count} 条");
                        foreach (var op in process)
                        {
                            Console.WriteLine($"工序路线: ID={op.Id}, Name={op.OperationName}");
                        }

                        // 设置数据源
                        Operation.Properties.DataSource = process;
                        // 在加载产线数据时
                        Operation.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                        Operation.Properties.DisplayMember = "OperationName";  // 数据源中的显示文本字段名
                        Operation.Properties.NullText = "请选择工序路线";

                        // 配置GridLookUpEdit的列 - 使用正确的方式
                        if (Operation.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                        {

                            // 清除现有列
                            gridView.Columns.Clear();



                            // 添加产线名称列
                            DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                            nameColumn.Caption = "工序路线";
                            nameColumn.FieldName = "OperationName";
                            nameColumn.Visible = true;
                            nameColumn.VisibleIndex = 0;

                            // 可选：设置列宽
                            nameColumn.Width = 150;

                            // 添加列到网格视图
                            gridView.Columns.Add(nameColumn);

                            // 禁用网格视图的分组面板
                            gridView.OptionsView.ShowGroupPanel = false;

                            // 设置行焦点样式
                            gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                            // 禁用单元格焦点外观
                            gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                        }
                    }
                    else
                    {
                        Console.WriteLine("工序路线数据为空");
                    }
                }
                else
                {
                    Console.WriteLine("工序路线API返回数据格式不正确，缺少pagingData字段");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载工序路线数据失败: {ex.Message}");
            }

        }

        /// <summary>
        /// 产品主数据下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowMasterData()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Product/GetProduct");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pageDatas"] != null)
            {
                string dataJson = jsonObject["pageDatas"].ToString();
                var process = JsonConvert.DeserializeObject<List<ProductModel>>(dataJson);

                // 设置数据源
                Masterdata.Properties.DataSource = process;
                // 在加载产线数据时
                Masterdata.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Masterdata.Properties.DisplayMember = "ProductName";  // 数据源中的显示文本字段名
                Masterdata.Properties.NullText = "请选择产品主数据";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Masterdata.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {

                    // 清除现有列
                    gridView.Columns.Clear();



                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "产品主数据";
                    nameColumn.FieldName = "ProductName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }

        }

        /// <summary>
        /// 产线下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowLine()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Line/GetLine");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pageDatas"] != null)
            {
                string dataJson = jsonObject["pageDatas"].ToString();
                var process = JsonConvert.DeserializeObject<List<LineModel>>(dataJson);

                // 设置数据源
                Line.Properties.DataSource = process;
                // 在加载产线数据时
                Line.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Line.Properties.DisplayMember = "LineName";  // 数据源中的显示文本字段名
                Line.Properties.NullText = "请选择所属产线";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Line.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {

                    // 清除现有列
                    gridView.Columns.Clear();



                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "产线名称";
                    nameColumn.FieldName = "LineName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }

        }

        /// <summary>
        /// 客户下拉
        /// </summary>
        /// <returns></returns>
        private async Task ShowClient()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Customer/GetCustomer");
            response.EnsureSuccessStatusCode();


            string responseBody = await response.Content.ReadAsStringAsync();
            var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            if (jsonObject["pageDatas"] != null)
            {
                string dataJson = jsonObject["pageDatas"].ToString();
                var process = JsonConvert.DeserializeObject<List<CustomerModel>>(dataJson);

                // 设置数据源
                Client.Properties.DataSource = process;
                // 在加载产线数据时
                Client.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                Client.Properties.DisplayMember = "CustomerName";  // 数据源中的显示文本字段名
                Client.Properties.NullText = "请选择所属客户";

                // 配置GridLookUpEdit的列 - 使用正确的方式
                if (Client.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                {
                    // 清除现有列
                    gridView.Columns.Clear();

                    // 添加产线名称列
                    DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                    nameColumn.Caption = "客户名称";
                    nameColumn.FieldName = "CustomerName";
                    nameColumn.Visible = true;
                    nameColumn.VisibleIndex = 0;

                    // 可选：设置列宽
                    nameColumn.Width = 150;

                    // 添加列到网格视图
                    gridView.Columns.Add(nameColumn);

                    // 禁用网格视图的分组面板
                    gridView.OptionsView.ShowGroupPanel = false;

                    // 设置行焦点样式
                    gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                    // 禁用单元格焦点外观
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                }
            }
        }
        #endregion


    }
}